//
//  FindFriendsViewController.m
//  SpendFunk
//
//  Created by dongmh on 4/20/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FindFriendsViewController.h"
#import "image.h"
#import "SpendFunkAppDelegate.h"
#import "Global.h"
#import "FbGraphFile.h"
#import "SA_OAuthTwitterEngine.h"
#import "MGTwitterEngine.h"
#define kOAuthConsumerKey				@"OusCDzDpQ0PfU7FCOCZDEg"		//REPLACE ME
#define kOAuthConsumerSecret			@"Qw3f4KJ0iEcu1W3vpsyLRfPdB23CCD8PYlLwM3F2WM"		//REPLACE ME
NSMutableArray *m_pArrMembers;
@implementation FindFriendsViewController
@synthesize fbGraph;

-(id)init
{
	m_pArrContent = [[NSArray alloc] initWithObjects:@"From my contact list", @"Facebook friends", @"Twitter friends",@"Search for users", @"Invite via SMS or Email", nil];
	m_pFBTWUsersID =[[NSMutableArray alloc] init];
    m_pUserEmail =[[NSMutableArray alloc] init];
    
    m_pArrContactList = [[NSMutableArray alloc] init];
	return self;
}
-(void)loadView
{
	[super loadView];
	[self initView];
}

-(void)initView
{
	/// backgrounnd for find friends screen
	NSString *path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
	UIImage *img = [UIImage imageNamed:path];
	UIImageView *imgvFFBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[imgvFFBkgr setImage:img];
	[self.view addSubview:imgvFFBkgr];
	[imgvFFBkgr setUserInteractionEnabled:YES];
	[imgvFFBkgr release];
	////	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_HEADER];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
	[imgvBar setImage:img];
	[self.view addSubview:imgvBar];
	[imgvBar setUserInteractionEnabled:YES];
	[imgvBar release];
	//back	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_BACK];
	img = [UIImage imageNamed:path];	
	m_pBtnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, img.size.width, img.size.height)];
	[m_pBtnBack setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnBack setBackgroundColor:[UIColor clearColor]];
	[m_pBtnBack setTitle:@"Back" forState:UIControlStateNormal];
	m_pBtnBack.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnBack addTarget:nil action:@selector(onClickBack) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnBack];
	///done
	//[path release];
//	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_NEXT];
//	img = [UIImage imageNamed:path];	
//	m_pBtnDone = [[UIButton alloc] initWithFrame:CGRectMake(320-5-img.size.width, 5, img.size.width, img.size.height)];
//	[m_pBtnDone setBackgroundImage:img forState:UIControlStateNormal];	
//	[m_pBtnDone setBackgroundColor:[UIColor clearColor]];
//	[m_pBtnDone setTitle:@"Done" forState:UIControlStateNormal];
//	[m_pBtnDone addTarget:nil action:@selector(onClickDone) forControlEvents:UIControlEventTouchUpInside];
//	[imgvBar addSubview:m_pBtnDone];
	
	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_TEXT_FFRIENDS];
	img = [UIImage imageNamed:path];
	UIImageView *imgvText = [[UIImageView alloc] initWithFrame:CGRectMake(320/2-img.size.width/2, 70, img.size.width, img.size.height)];
	[imgvText setImage:img];
	[self.view addSubview:imgvText];
	[imgvText setUserInteractionEnabled:YES];
	[imgvText release];
	///
	
	int nHRow = 46;
	m_pTableFindFriends = [[UITableView alloc] initWithFrame:CGRectMake(10,100, 300, 4*46+60) style:UITableViewStyleGrouped];
	m_pTableFindFriends.delegate =self;
	m_pTableFindFriends.dataSource = self;
	m_pTableFindFriends.rowHeight = nHRow;
	[m_pTableFindFriends setShowsVerticalScrollIndicator:NO];
	[m_pTableFindFriends setBackgroundColor:[UIColor clearColor]];
	[self.view addSubview:m_pTableFindFriends];
	[m_pTableFindFriends release];
	[m_pTableFindFriends reloadData];
	m_pTableFindFriends.scrollEnabled = YES;
	
	// Please wait ... 
	_blockerView = [[[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 60)] autorelease];
	_blockerView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.8];
	_blockerView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
	_blockerView.alpha = 0.0;
	_blockerView.clipsToBounds = YES;
	if ([_blockerView.layer respondsToSelector: @selector(setCornerRadius:)]) [(id) _blockerView.layer setCornerRadius: 10];
	
	UILabel	*label = [[[UILabel alloc] initWithFrame: CGRectMake(0, 5, _blockerView.bounds.size.width, 15)] autorelease];
	label.text = NSLocalizedString(@"Please Wait…", nil);
	label.backgroundColor = [UIColor clearColor];
	label.textColor = [UIColor whiteColor];
	label.textAlignment = UITextAlignmentCenter;
	label.font = [UIFont boldSystemFontOfSize: 15];
	[_blockerView addSubview: label];
	
	UIActivityIndicatorView				*spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite] autorelease];
	
	spinner.center = CGPointMake(_blockerView.bounds.size.width / 2, _blockerView.bounds.size.height / 2 + 10);
	[_blockerView addSubview: spinner];
	[self.view addSubview: _blockerView];
	[spinner startAnimating];
}

-(void)setKeyBroadActive{
	
}


-(void)onClickBack
{
	[g_AppDelegate goBackHome:self.view];
	//[g_AppDelegate openLogin];
}
-(void)onClickDone
{
	//[g_AppDelegate openFeaturedMembers];
}


#pragma mark textfield delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
	return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}


#pragma mark tableViewdelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [m_pArrContent count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = nil;
	cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"3"];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"3"] autorelease];
		NSString *sImg = [[NSString alloc] initWithFormat:@""];
		cell.imageView.image = [UIImage imageNamed:sImg];
		cell.textLabel.text = [m_pArrContent objectAtIndex:indexPath.row];
		[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
		[sImg release];
	}
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
#pragma mark doan nay se kiem tra xem click vao cell loai j
	//demo se chuyen luon sang view Featured Members
	//NSArray *arrtemp = [[NSArray alloc] initWithObjects:@"anhlh",@"emlh",@"be vi",nil];
    //	[g_AppDelegate openFeaturedMembersWithMembers:arrtemp];
	
	switch (indexPath.row) {
		case 0:	
        {
			// Scan from address book	
			_blockerView.alpha =1.0;
			g_iMode = MODE_CONTACT_LIST;
			m_pUserEmail = [self getInfoContactList];
			
			//[g_AppDelegate openFeaturedMembersWithMembers:m_pUserEmail];
		}
			break;
		case 1:				// Login facebook
			g_iMode = MODE_FACEBOOK;
			[self displayFacebook];
			break;
		case 2:
        {
			// Login twitter
			g_iMode = MODE_TWITTER;
			[self displayTwitter];
		}	
			break;
			
		case 3: // Search users
			//_blockerView.alpha =1.0;
			g_iMode = MODE_SEARCHUSER;
			[g_AppDelegate openSearchforUsers];	
			break;
			
		case 4:	// Invite via sms/email
        {
			g_iMode = MODE_INVITE;
            [self getInfoContactList];
            [g_AppDelegate openListContact];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ListContact" object:m_pArrContactList];
		}			
			
			break;
	}
}


//- (void)viewDidAppear:(BOOL)animated{
//	if (!_engine) {
//		return;
//	}else {
//		//[_engine getFollowersIncludingCurrentStatus:10];
//		_engine = nil;
//	}
//    
//	
//}


//----------------- NTQUAN
///////---------------------CONTACT LIST-----------------//
#pragma mark CONTACT LIST
-(NSMutableArray*)getInfoContactList
{
    NSString *personName;
    
    NSMutableArray *arrayEmail = [[NSMutableArray alloc] init];
    NSMutableDictionary *pDicContactList;
    NSArray  *pArrObjectContact;
    NSArray  *pArrKeysContact = [NSArray arrayWithObjects:@"kName",@"kPhone",@"kEmail",@"kImage",nil];
    [m_pArrContactList removeAllObjects];
    
    // Fetch the address book
    ABAddressBookRef addressBook = ABAddressBookCreate();
    // get all people from the addressbook
    NSArray *people = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
    if ((people != nil) && [people count]) {
        NSLog(@"%d contacts have been extracted from the address book", [people count]);
        for (int i=0;i < [people count];i++)
        {
            ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
            //get name
            CFStringRef cfName = ABRecordCopyCompositeName(person);
            personName = [NSString stringWithString:(NSString *)cfName]; //ten trong danh ba
            CFRelease(cfName);
            
            //get phone number
            ABMultiValueRef phoneNumber = ABRecordCopyValue(person, kABPersonPhoneProperty);
            NSArray *arrPhone = (NSArray *)ABMultiValueCopyArrayOfAllValues(phoneNumber);
			if (!arrPhone) {
				arrPhone = [[NSArray alloc] init];
			}
            
            //get email
            ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
            NSArray *arrMailAdresses = (NSArray *)ABMultiValueCopyArrayOfAllValues(emails);
			if (!arrMailAdresses) {
				arrMailAdresses = [[NSArray alloc] init];
			}
            NSLog(@"contact %d  %@ has %d E-Mail addresses",i,personName,[arrMailAdresses count]);
            NSString *emailAddress = nil;
            for (int j=0;j < [arrMailAdresses count];j++) 
            {
                emailAddress = (NSString *)[arrMailAdresses objectAtIndex:j];
                NSLog(@"address %d: %@", j, emailAddress);
				[arrayEmail addObject:emailAddress];
            }
            
            //get image
            UIImage *image = nil;
            if(ABPersonHasImageData(person))
            {
                image = [UIImage imageWithData:(NSData *)ABPersonCopyImageData(person)];
            }
            else
            {
                //default image in contact list
                NSString *path = [NSString stringWithFormat:@"%@",IMG_BKGR_VIEW];
                image = [UIImage imageNamed:path];
                
            }
            
            pArrObjectContact = [NSArray arrayWithObjects:personName,arrPhone,arrMailAdresses,image,nil];
            
            pDicContactList = [NSDictionary dictionaryWithObjects:pArrObjectContact forKeys:pArrKeysContact];
            [m_pArrContactList addObject:pDicContactList];
            
        }
		//
		//if (g_iMode == MODE_INVITE) {
//				[g_AppDelegate openFeaturedMembersWithMembers:[m_pArrContactList valueForKey:@"kEmail"]];
//		}
		if (g_iMode == MODE_CONTACT_LIST) {
			[self getFriendsInFriendidList:arrayEmail];
		}
		//[g_AppDelegate openFeaturedMembersWithMembers:[m_pArrContactList valueForKey:@"kEmail"]];
    } 
    else 
    {
        NSLog(@"No contacts have been extracted from the address book");        
    }
    [people release];
    CFRelease(addressBook);
    return arrayEmail;
}

//////--------------------------FACEBOOK----------------------//
#pragma mark FACEBOOK
-(void)displayFacebook
{
    //logout
    NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray* facebookCookies = [cookies cookiesForURL:
                                [NSURL URLWithString:@"http://login.facebook.com"]];
    
    for (NSHTTPCookie* cookie in facebookCookies) {
        [cookies deleteCookie:cookie];
    }
    
    /*Facebook Application ID*/
	NSString *client_id = @"ab7544c6692dd7309d596640027f8ab3";
	
	//alloc and initalize our FbGraph instance
	self.fbGraph = [[FbGraph alloc] initWithFbClientID:client_id];
	
	//begin the authentication process.....
	[fbGraph authenticateUserWithCallbackObject:self andSelector:@selector(fbGraphCallback:) 
						 andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];
}

#pragma mark -
#pragma mark FbGraph Callback Function
/**
 * This function is called by FbGraph after it's finished the authentication process
 **/
- (void)fbGraphCallback:(id)sender {
	
	if ( (fbGraph.accessToken == nil) || ([fbGraph.accessToken length] == 0) ) {
		
		NSLog(@"You pressed the 'cancel' or 'Dont Allow' button, you are NOT logged into Facebook...I require you to be logged in & approve access before you can do anything useful....");
		
		//restart the authentication process.....
		[fbGraph authenticateUserWithCallbackObject:self andSelector:@selector(fbGraphCallback:) 
							 andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];
		
	} else {
		//login success
        NSLog(@"------------>CONGRATULATIONS<------------, You're logged into Facebook...  Your oAuth token is:  %@", fbGraph.accessToken);
        [self getMeFriends];	
	}
	
}



//get name and id
-(void)getMeFriends
{
    [self getMyID];
    NSString *strTemp = nil;
    NSArray *arrTemp;
    
	FbGraphResponse *fb_graph_response = [fbGraph doGraphGet:@"me/friends" withGetVars:nil];
	//NSLog(@"getMeFriendsButtonPressed:  %@", fb_graph_response.htmlResponse);
    
    
    ////Parse string to get name and ID
    NSString *strFriends = fb_graph_response.htmlResponse;
    NSArray *listItems = [strFriends componentsSeparatedByString:@"id\":\""];
    //NSLog(@"1 phan tu: %@",[listItems objectAtIndex:1]);
    
    for (int i = 1 ; i < [listItems count]; i++) 
    {
        strTemp = [listItems objectAtIndex:i];
        //NSLog(@"Chuoi tach cap 1 %@",strTemp);
        arrTemp = [strTemp componentsSeparatedByString:@"\""];
        //NSLog(@"id la: %@",[arrTemp objectAtIndex:0]);
        [m_pFBTWUsersID addObject:[arrTemp objectAtIndex:0]];
    }
	_blockerView.alpha = 0.0;
	[self getFriendsInFriendidList:m_pFBTWUsersID];
	//[g_AppDelegate openFeaturedMembersWithMembers:m_pFBTWUsersID];
}

//post picture
-(void)postPictureToFacebook:(UIImage*)image
{
	
	NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:3];
	
	//create a FbGraphFile object insance and set the picture we wish to publish on it
	FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:image];
	
	//finally, set the FbGraphFileobject onto our variables dictionary....
	[variables setObject:graph_file forKey:@"file"];
	
	[variables setObject:@"This is my Pic" forKey:@"message"];
	
	//the fbGraph object is smart enough to recognize the binary image data inside the FbGraphFile
	//object and treat that is such.....
	[fbGraph doGraphPost:@"me/photos" withPostVars:variables];
	
	NSLog(@"Now log into Facebook and look at your profile & photo albums...");
	
}	

-(void)getMyID 
{
	NSString *strTemp = nil;
    NSArray *arrTemp;
	
	FbGraphResponse *fb_graph_response = [fbGraph doGraphGet:@"me" withGetVars:nil];
	NSLog(@"thong tin cua chinh minh :  %@", fb_graph_response.htmlResponse);
	
	NSString *strFriends = fb_graph_response.htmlResponse;
	NSArray *listItems = [strFriends componentsSeparatedByString:@"id\":\""];
    //NSLog(@"1 phan tu: %@",[listItems objectAtIndex:1]);
    
	strTemp = [listItems objectAtIndex:0];
	//NSLog(@"Chuoi tach cap 1 %@",strTemp);
	arrTemp = [strTemp componentsSeparatedByString:@"\""];
	//NSLog(@"id la: %@",[arrTemp objectAtIndex:0]);
	g_strFacebookId = [arrTemp objectAtIndex:0];
    
	[self getInforUser];
}

-(void)getInforUser{
	m_pUserPro = [[UserProfile alloc] init];
	[m_pUserPro getUserProfile];
}

//////-------------TWITTWER---------------------------//
#pragma mark TWITTWER
- (void)displayTwitter{
	if (_engine) return;
	
	//g_iMode = MODE_TWITTER;
	_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
	_engine.consumerKey = kOAuthConsumerKey;
	_engine.consumerSecret = kOAuthConsumerSecret;
	
	UIViewController	*controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
	
	//if (controller) 
	[self presentModalViewController: controller animated: YES];
	//else {
	//	[_engine sendUpdate: [NSString stringWithFormat: @"Already Updated. %@", [NSDate date]]];
	//}
	[_engine clearsCookies];
	_blockerView.alpha =1.0;
	//[controller release];
}
#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
	NSLog(@"Authenicated for %@", username);
	if (!username) {
		_blockerView.alpha =0.0;
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Request time out" message:@"Please try againt later" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return;
	}else {
		[_engine getFollowersIncludingCurrentStatus:1];
		
	}
}

- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
	NSLog(@"Authentication Failed!");

}

- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
	NSLog(@"Authentication Canceled.");
	_blockerView.alpha = 0.0;
}

- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
	NSLog(@"Request %@ failed with error: %@", requestIdentifier, error);
}

#pragma mark MGTwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
	NSLog(@"Request %@ succeeded", requestIdentifier);
	
}
- (void)userInfoReceived:(NSArray *)userInfo forRequest:(NSString *)connectionIdentifier{
	NSArray *arr = nil;
	arr	= [userInfo retain];
	_blockerView.alpha =0.0;
	_engine = nil;
	if ([userInfo count] == 0) { // if no friend show alert
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Not found" message:@"Please try againt later" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}else {// if have get listfriend
		NSArray *pArr = [arr valueForKey:@"id"];
		for (int i = 0; i<[pArr count]; i++) {
			[m_pFBTWUsersID addObject:[pArr objectAtIndex:i]];
			NSLog(@"id twitter: %@",[m_pFBTWUsersID objectAtIndex:i]);
		}
		[self getFriendsInFriendidList:m_pFBTWUsersID];
		//[g_AppDelegate openFeaturedMembersWithMembers:m_pFBTWUsersID];
	}
	_engine = nil;
}
#pragma mark getFriendsInFriendidList
- (void)getFriendsInFriendidList:(NSArray*)members{
	iCurrCount = 0;
	iCountFriend = 0;
	
	if([members count]<1 || members==nil){
		if(m_pArrMembers){
			[m_pArrMembers release];
			m_pArrMembers = nil;
		}
		//m_pArrMembers = [members retain];
		return;
	}
	if(m_pArrMembers){
		[m_pArrMembers release];
		m_pArrMembers = nil;
	}
	m_pArrMembers = [members retain];
	
	NSLog(@"%s",[members objectAtIndex:0]);
	NSString *strAllMembers = [[NSString alloc] initWithString:[members objectAtIndex:0]];
	if([members count] == 1)
	{
		
	}
	else
	{
		for(int i = 1; i < [members count]; i++){
			strAllMembers = [NSString stringWithFormat:@"%@,%@",strAllMembers,[members objectAtIndex:i]];
		}
		strAllMembers = [NSString stringWithFormat:@"%@,%@", g_strFacebookId, strAllMembers];
	}
	
	//default g_iMode = 0
	NSString *post = nil;
	NSData *postData = nil;
	NSString *postLength = nil; 
	NSURL *url = nil;
	if(g_iMode == MODE_CONTACT_LIST)
	{
		post = [NSString stringWithFormat:@"userid=%@&str_email=%@", g_strLoginUserId, strAllMembers];
		postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
		postLength = [NSString stringWithFormat:@"%d", [postData length]];
		url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/contactlist"];
	}
	else if(g_iMode == MODE_FACEBOOK)
	{
		//post = [NSString stringWithFormat:@"userid=%@&str_facebookid=%@", g_strLoginUserId, strAllMembers];
		post = @"";
		//post = [NSString stringWithFormat:@"userid=%@&str_facebookid=100000596976260,2,345", g_strLoginUserId];
		//post = [NSString stringWithFormat:@"userid=9&str_facebookid=100000813954361,4,123456"];
		postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
		postLength = [NSString stringWithFormat:@"%d", [postData length]];
		url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/facebookcontact"];
	}
	else if(g_iMode == MODE_TWITTER)
	{
		post = [NSString stringWithFormat:@"userid=%@&str_twitterid=%@", g_strLoginUserId, strAllMembers];
		postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
		postLength = [NSString stringWithFormat:@"%d", [postData length]];
		url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/twittercontact"];
	}
	NSLog(@"%@",post);
	
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];  
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
	[theRequest setHTTPBody:postData];	
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if( theConnection )
	{
		m_pWebData = [[NSMutableData data] retain];
		isContinueParse = true;
		
		if(!m_pArrFriends){
			m_pArrFriends = [[NSMutableArray alloc] init];
		}else {
			[m_pArrFriends removeAllObjects];
		}
		
	}
	else
	{
		
	}
}

#pragma mark delegate connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_pWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_pWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect to internet" message:@"Please connect to internet!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	
	[alert release];
	[connection release];
	[m_pWebData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSData *loginStatus = [[NSData alloc] initWithBytes: [m_pWebData mutableBytes] length:[m_pWebData length]];
	
	NSString *a = [[NSString alloc] initWithData:loginStatus encoding:NSUTF8StringEncoding];
	NSLog(@"%@",a);
	
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:loginStatus];
	[xmlParser setDelegate:self];
	
	BOOL success = [xmlParser parse];
	
	if(success)
	{
		_blockerView.alpha =0.0;
		NSLog(@"No Errors");
		if ([m_pArrFriends count] == 0) {
			UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Not found friends" message:@"Please try againt later" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
			[alertView release];
		}else {
			[g_AppDelegate openFeaturedMembersWithMembers:m_pArrFriends];
		}

		
	}
	else
	{
		NSLog(@"Error Error Error!!!");
	}
	
	[connection release];
	[m_pWebData release];
}

#pragma mark delegate xmlParser
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if(!currentElement) 
		currentElement = [[NSString alloc] initWithString:elementName];
	else
		currentElement = [elementName retain];
	
	NSLog(@"Processing Element: %@", elementName);
	
	//iCurrCount = iCountFriend;
	if([currentElement isEqualToString:kUserID]){
		iCountFriend++;
		if(iCountFriend >=2){
			[m_pArrFriends addObject:m_pDictUserInfo];
		}
		[m_pDictUserInfo release];
		m_pDictUserInfo = nil;
		m_pDictUserInfo = [[NSMutableDictionary alloc] init];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	NSLog(@"Processing Value: %@", string);
	
	if([currentElement isEqualToString:kUserID]){
		[m_pDictUserInfo setObject:string forKey:kUserID];
	}
	if([currentElement isEqualToString:kUserName]){
		[m_pDictUserInfo setObject:string forKey:kUserName];
	}
	if([currentElement isEqualToString:kFirstName]){
		[m_pDictUserInfo setObject:string forKey:kFirstName];
	}
	if([currentElement isEqualToString:kLastName]){
		[m_pDictUserInfo setObject:string forKey:kLastName];
	}
	if([currentElement isEqualToString:kEmail]){
		[m_pDictUserInfo setObject:string forKey:kEmail];
	}
	if([currentElement isEqualToString:kAvatar]){
		[m_pDictUserInfo setObject:string forKey:kAvatar];
	}
	if([currentElement isEqualToString:kUserType]){
		[m_pDictUserInfo setObject:string forKey:kUserType];
	}
	if([currentElement isEqualToString:kFacebookID]){
		[m_pDictUserInfo setObject:string forKey:kFacebookID];
	}
	if([currentElement isEqualToString:kTwitterID]){
		[m_pDictUserInfo setObject:string forKey:kTwitterID];
	}
	if([currentElement isEqualToString:kFollow]){
		[m_pDictUserInfo setObject:string forKey:kFollow];
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	[currentElement release];
	currentElement = nil;
	[currentElementValue release];
	currentElementValue = nil;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
